using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Data;
using Models;

namespace Services
{
    /// <summary>
    /// 权限服务实现类，处理所有权限相关的业务逻辑
    /// </summary>
    public class PermissionService : IPermissionService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ICacheService _cacheService;
        /// <summary>
        /// 用户权限缓存键模板，{0}为用户ID
        /// </summary>
        private const string PERMISSION_CACHE_KEY = "user_permissions_{0}";
        /// <summary>
        /// 角色权限缓存键模板，{0}为角色ID
        /// </summary>
        private const string ROLE_PERMISSIONS_CACHE_KEY = "role_permissions_{0}";

        /// <summary>
        /// 构造函数，注入所需服务
        /// </summary>
        public PermissionService(
            ApplicationDbContext dbContext,
            ICacheService cacheService)
        {
            _dbContext = dbContext;
            _cacheService = cacheService;
        }

        /// <summary>
        /// 获取用户的所有权限
        /// </summary>
        public async Task<List<string>> GetUserPermissionsAsync(int userId)
        {
            var cacheKey = string.Format(PERMISSION_CACHE_KEY, userId);
            
            return await _cacheService.GetOrCreateAsync(cacheKey, async () =>
            {
                // 通过LINQ查询获取用户的所有权限
                return await (from ur in _dbContext.UserRoles
                            join rp in _dbContext.RolePermissions on ur.RoleId equals rp.RoleId
                            join p in _dbContext.Permissions on rp.PermissionId equals p.PermissionId
                            where ur.UserId == userId
                            select p.PermissionName).Distinct().ToListAsync();
            });
        }

        /// <summary>
        /// 检查用户是否拥有指定权限
        /// </summary>
        public async Task<bool> HasPermissionAsync(int userId, string permission)
        {
            var permissions = await GetUserPermissionsAsync(userId);
            return permissions.Contains(permission);
        }

        /// <summary>
        /// 使用户的权限缓存失效
        /// </summary>
        public async Task InvalidateUserPermissionsCacheAsync(int userId)
        {
            var cacheKey = string.Format(PERMISSION_CACHE_KEY, userId);
            await _cacheService.RemoveAsync(cacheKey);
        }

        /// <summary>
        /// 将用户添加到指定角色
        /// </summary>
        public async Task AddUserToRoleAsync(int userId, int roleId)
        {
            var existingUserRole = await _dbContext.UserRoles
                .FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId);

            if (existingUserRole == null)
            {
                _dbContext.UserRoles.Add(new UserRole
                {
                    UserId = userId,
                    RoleId = roleId
                });
                await _dbContext.SaveChangesAsync();
                await InvalidateUserPermissionsCacheAsync(userId);
            }
        }

        /// <summary>
        /// 从指定角色中移除用户
        /// </summary>
        public async Task RemoveUserFromRoleAsync(int userId, int roleId)
        {
            var userRole = await _dbContext.UserRoles
                .FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId);

            if (userRole != null)
            {
                _dbContext.UserRoles.Remove(userRole);
                await _dbContext.SaveChangesAsync();
                await InvalidateUserPermissionsCacheAsync(userId);
            }
        }

        /// <summary>
        /// 为角色添加权限
        /// </summary>
        public async Task AddPermissionToRoleAsync(int roleId, string permissionName)
        {
            // 获取或创建权限
            var permission = await _dbContext.Permissions
                .FirstOrDefaultAsync(p => p.PermissionName == permissionName);

            if (permission == null)
            {
                permission = new Permission { PermissionName = permissionName };
                _dbContext.Permissions.Add(permission);
                await _dbContext.SaveChangesAsync();
            }

            // 检查角色权限关联是否已存在
            var existingRolePermission = await _dbContext.RolePermissions
                .FirstOrDefaultAsync(rp => rp.RoleId == roleId && rp.PermissionId == permission.PermissionId);

            if (existingRolePermission == null)
            {
                _dbContext.RolePermissions.Add(new RolePermission
                {
                    RoleId = roleId,
                    PermissionId = permission.PermissionId
                });
                await _dbContext.SaveChangesAsync();

                // 使该角色的所有用户的权限缓存失效
                var userIds = await _dbContext.UserRoles
                    .Where(ur => ur.RoleId == roleId)
                    .Select(ur => ur.UserId)
                    .ToListAsync();

                foreach (var userId in userIds)
                {
                    await InvalidateUserPermissionsCacheAsync(userId);
                }

                // 使角色权限缓存失效
                await InvalidateRolePermissionsCacheAsync(roleId);
            }
        }

        /// <summary>
        /// 从角色中移除权限
        /// </summary>
        public async Task RemovePermissionFromRoleAsync(int roleId, string permissionName)
        {
            var permission = await _dbContext.Permissions
                .FirstOrDefaultAsync(p => p.PermissionName == permissionName);

            if (permission != null)
            {
                var rolePermission = await _dbContext.RolePermissions
                    .FirstOrDefaultAsync(rp => rp.RoleId == roleId && rp.PermissionId == permission.PermissionId);

                if (rolePermission != null)
                {
                    _dbContext.RolePermissions.Remove(rolePermission);
                    await _dbContext.SaveChangesAsync();

                    // 使该角色的所有用户的权限缓存失效
                    var userIds = await _dbContext.UserRoles
                        .Where(ur => ur.RoleId == roleId)
                        .Select(ur => ur.UserId)
                        .ToListAsync();

                    foreach (var userId in userIds)
                    {
                        await InvalidateUserPermissionsCacheAsync(userId);
                    }

                    // 使角色权限缓存失效
                    await InvalidateRolePermissionsCacheAsync(roleId);
                }
            }
        }

        /// <summary>
        /// 获取角色的所有权限
        /// </summary>
        public async Task<List<string>> GetRolePermissionsAsync(int roleId)
        {
            var cacheKey = string.Format(ROLE_PERMISSIONS_CACHE_KEY, roleId);
            
            return await _cacheService.GetOrCreateAsync(cacheKey, async () =>
            {
                return await _dbContext.RolePermissions
                    .Where(rp => rp.RoleId == roleId)
                    .Join(_dbContext.Permissions,
                        rp => rp.PermissionId,
                        p => p.PermissionId,
                        (rp, p) => p.PermissionName)
                    .ToListAsync();
            });
        }

        /// <summary>
        /// 使角色权限缓存失效
        /// </summary>
        private async Task InvalidateRolePermissionsCacheAsync(int roleId)
        {
            var cacheKey = string.Format(ROLE_PERMISSIONS_CACHE_KEY, roleId);
            await _cacheService.RemoveAsync(cacheKey);
        }
    }
} 